import { login, logout, getInfo, getCircleLogo } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { getUserProfileApi } from "@/wss/newApi_3-24/system/user.js";
import { getcircleuserBalanceApi } from "@/BMViews/api/financial/deposit.js";
import { getBudgetServiceListApi } from "@/BMViews/api/budget/budgetService.js";
import { getBudgetRoleListApi } from "@/BMViews/api/budget/budgetRole.js";
import { getselectUserByCircleApi } from "@/BMViews/api/service/circle.js";
const user = {
  state: {
    token: getToken(),
    name: "",
    status: "",
    userId: "",
    avatar: "",
    roles: [],
    permissions: [],
    userInfo: {},
    circleId: "", //自己的问圈id
    circleLogo: "", //问圈logo
    budgetService: {}, //阿米巴预算服务
    budgetRole: {}, //阿米巴预算角色
    circleStaffList: [], //问圈圈员列表
    address:{},//定位
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_EMAIL: (state, email) => {
      state.email = email;
    },
    // 设置商务id
    SET_CMID: (state, cmId) => {
      state.cmId = cmId;
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo;
    },
    SET_PHONENUMBER: (state, phonenumber) => {
      state.phonenumber = phonenumber;
    },
    SET_CIRCLEID(state, circleId) {
      state.circleId = circleId;
    },
    SET_USERID: (state, userId) => {
      state.userId = userId;
    },
    SET_STATUS: (state, status) => {
      state.status = status;
    },
    SET_TYPE: (state, userType) => {
      state.userType = userType;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    // 设置问圈logo
    SET_CIRCLELOGO: (state, circleLogo) => {
      state.circleLogo = circleLogo;
    },
    // 设置阿米巴预算服务
    SET_BUDGETSERVICE: (state, budgetService) => {
      state.budgetService = budgetService;
    },
    // 设置阿米巴预算角色
    SET_BUDGETROLE: (state, budgetRole) => {
      state.budgetRole = budgetRole;
    },
    // 设置问圈圈员列表
    SET_CIRCLESTAFF: (state, circleStaffList) => {
      state.circleStaffList = circleStaffList;
    },
    // 定位
    SET_ADDRESS:(state,address)=>{
       state.address=address;
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;

      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then(res => {
            setToken(res.token);

            commit("SET_TOKEN", token);
            // 获取当前用户的问圈id

            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 登录
    codeLogin({ commit }, token, userId) {
      // const username = userInfo.username.trim()
      // const password = userInfo.password
      // const code = userInfo.code
      // const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        setToken(token);
        // setToken(userId);
        commit("SET_TOKEN", token);
        // commit("SET_USERID", userId);
        localStorage.setItem("token", token);
        // localStorage.setItem("userId", userId);
        resolve();
      });
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(res => {
            const user = res.user;
            // const avatar = user.avatar == "" ? require("@/assets/images/profile.jpg") : process.env.VUE_APP_BASE_API + user.avatar;
            const avatar =
              user.avatar == ""
                ? require("@/assets/images/defaultAvatar.jpg")
                : user.avatar;

            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit("SET_ROLES", res.roles);
              commit("SET_PERMISSIONS", res.permissions);
            } else {
              commit("SET_ROLES", ["ROLE_DEFAULT"]);
            }
            getcircleuserBalanceApi(user.phonenumber).then(({ data }) => {
              commit("SET_CIRCLEID", data.circleId);
            });
            // 获取当前问圈logo
            getCircleLogo().then(res => {
              // console.log(res,'获取当前问圈logo circleLogo');
              commit("SET_CIRCLELOGO", res.msg);
            });
            commit("SET_USERINFO", user);
            commit("SET_TYPE", user.userType);
            commit("SET_NAME", user.userName);
            commit("SET_PHONENUMBER", user.phonenumber);
            commit("SET_EMAIL", user.email);
            commit("SET_STATUS", user.status);
            commit("SET_USERID", user.userId);
            localStorage.setItem("userId", user.userId);
            commit("SET_AVATAR", avatar);
            commit("SET_CMID", user.cmId);

            resolve(res);
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    //获取问圈圈员列表
    async getCircleStaffList({ commit, state }) {
      if (state.userInfo.whereCircleId) {
        const params = {
          circleId: state.userInfo.whereCircleId,
          type: "1"
        };
        let res = await getselectUserByCircleApi(params);
        console.log("圈员列表", res.rows);
        if (res.code == 200) {
          let list = res.rows;
          list.forEach(v => {
            v.name = v.nickname;
          });
          commit("SET_CIRCLESTAFF", list);
        }
      }
    },
    // 获取阿米巴预算的服务对象
    async getBudget({ commit, state }) {
      console.log(state.userInfo.whereCircleId,'获取阿米巴预算的服务对象');
      if (state.userInfo.whereCircleId) {
        let circle_id = state.userInfo.whereCircleId;
        let res = await getBudgetServiceListApi({ circle_id });
        if (res.code == 200) {
          commit("SET_BUDGETSERVICE", res.rows[0] || {});
        }
      }
    },
    // 获取阿米巴预算的角色
    async getBudgetRole({ commit, state }) {
      console.log(state.userInfo.whereCircleId,'获取阿米巴预算的角色');
      if (state.userInfo.whereCircleId) {
        let data = {
          circle_id: state.userInfo.whereCircleId,
          user_id: state.userInfo.userId
        };
        let res = await getBudgetRoleListApi(data);
        if (res.code == 200) {
          commit("SET_BUDGETROLE", res.rows[0] || {});
        }
      }
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        state.avatar = "";
        logout(state.token)
          .then(() => {
            commit("SET_TOKEN", ""); //清空token
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            commit("SET_BUDGETSERVICE", {}); //数据持久化 退出前清空阿米巴预算服务对象
            commit("SET_BUDGETROLE", {}); //数据持久化 退出前清空阿米巴预算角色
            commit("SET_PERMISSIONS", []);
            removeToken();
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit("SET_TOKEN", "");
        removeToken();
        resolve();
      });
    },
    // 定位
    getAddress({ commit }){
        try{
        
           const geolocation =new BMap.Geolocation();
            geolocation.getCurrentPosition(function(r){
            console.log(r,"aaaa");
            if(this.getStatus() == BMAP_STATUS_SUCCESS){
                const{lat =null, lng=null} = r.point;
            }
            commit("SET_ADDRESS", r.address);
        });
        }catch(e){
            console.log(e)
        }
    }
    
  }
};

export default user;
